# -*- coding: utf-8 -*
'''
    Created by XiaoInk at 2021/10/08 23:06:54
    Gitee: https://gitee.com/XiaoInk
'''

import os
import shutil
import hashlib

from flask import Blueprint, request, make_response, send_from_directory
from flask.json import jsonify

from app.macros import macros
from app.config import get_config

bp = Blueprint('file', __name__)

conf = get_config(os.getenv('ENV', 'local'))

# 允许上传的文件类型
ALLOWED_EXTENSIONS = set(['image/png', 'image/jpg', 'image/jpeg', 'image/webp', 'application/octet-stream'])


@bp.route('/upload', methods=['POST'])
def upload():
    '''文件上传'''
    files = request.files.getlist('file')

    if not files:
        return jsonify(code=macros.HTTP.StatusBadRequest, msg='必传参数不能为空')

    mdfs = []
    for file in files:
        # 检测文件是否存在、类型是否合法
        if not file or file.mimetype not in ALLOWED_EXTENSIONS:
            continue
        # 获取文件后缀
        _, suffix = os.path.splitext(file.filename)
        # 获取文件MD5
        MD5 = hashlib.md5(file.stream.read()).hexdigest()
        # 生成新文件名
        filename = f'{MD5}{suffix}'
        file.stream.seek(0)
        file.save(f'{macros.CMS.FileUploadDir}/{filename}')
        mdfs.append(filename)

    if not mdfs:
        return jsonify(code=macros.HTTP.StatusBadRequest, msg='文件上传失败')

    return jsonify(code=macros.HTTP.StatusOK, msg='文件上传成功', data=mdfs)


@bp.route('/download/v1/<string:filename>', methods=['GET'])
def download_v1(filename: str):
    '''文件下载, 以静态文件的方式返回'''
    if not os.path.isfile(f'{macros.CMS.FileUploadDir}/{filename}'):
        return jsonify(code=macros.HTTP.StatusNotFound, msg='文件不存在')

    shutil.copyfile(f'{macros.CMS.FileUploadDir}/{filename}', f'{macros.CMS.FileDownloadDir}/{filename}')

    return jsonify(code=macros.HTTP.StatusOK, msg='ok', url=f'{conf.DOMAIN}/download/{filename}')


@bp.route('/download/v2/<string:filename>', methods=['GET'])
def download_v2(filename: str):
    '''文件下载, 以动态路由的方式返回文件'''
    response = make_response(send_from_directory(macros.CMS.FileUploadDir, filename, as_attachment=True))
    response.headers['Content-Disposition'] = ['inline']
    return response


if __name__ == '__main__':
    pass
